import pathToRegexp from 'path-to-regexp';
import { queryDepartmentList, queryDept } from '../services/register';

export default {
  namespace: 'deptList',
  state: {
    depts: [],
    department: [],
  },
  reducers: {
    fetchDeptListSuccess(state, { payload }) {
      return {
        ...state,
        depts: payload,
      };
    },
    queryDeptValue(state, { payload }) {
      return {
        ...state,
        department: payload,
      };
    },
  },
  effects: {
    *fetchDeptList({
      payload,
    }, { put, call }) {
      const { data } = yield call(queryDepartmentList, payload);
      const list = data.data.map((d) => {
        return {
          name: d.departName,
          code: d.departCode,
        };
      });
      yield put({
        type: 'fetchDeptListSuccess',
        payload: list,
      });
    },
    *queryDept({ payload }, { call, put }) {
      const { data } = yield call(queryDept, payload);
      yield put({
        type: 'queryDeptValue',
        payload: data.data,
      });
    },
  },
  subscriptions: {
    setup({ dispatch, history }) {
      history.listen((location) => {
        const match = pathToRegexp('/selectDept').exec(location.pathname);
        if (match) {
          // dispatch({
          //   type: 'fetchDeptList',
          //   payload: {
          //     isIncludeNopItem: false,
          //   },
          // });
          dispatch({
            type: 'queryDept',
            payload: {
              isIncludeNopItem: false,
            },
          });
        }
      });
    },
  },
};
